<?php
/**
 * @version		$Id: media.php 10381 2008-06-01 03:35:53Z pasamio $
 * @package		Joomla
 * @subpackage	Media
 * @copyright	Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant to the
 * GNU General Public License, and as distributed it includes or is derivative
 * of works licensed under the GNU General Public License or other free or open
 * source software licenses. See COPYRIGHT.php for copyright notices and
 * details.
 */

/**
 * @package		Joomla
 * @subpackage	Media
 */
class XlsHelper
{
    function upload($file,$filepath)
    {
        global $mainframe;

        // Check for request forgeries
        //JRequest::checkToken( 'request' ) or jexit( 'Invalid Token' );

//        $file 		= JRequest::getVar( 'Filedata', '', 'files', 'array' );
//        $folder		= JRequest::getVar( 'folder', '', '', 'path' );
        $err		= null;
        
        // Set FTP credentials, if given
        jimport('joomla.client.helper');
        JClientHelper::setCredentialsFromRequest('ftp');

        // Make the filename safe
        jimport('joomla.filesystem.file');
        $file['name']	= JFile::makeSafe($file['name']);
        if (isset($file['name'])) {
            if (!$this->canUpload( $file, $err )) {
                $mainframe->redirect('index.php?option=com_sim&task=edit&controller=sim', 'Không thể upload file.Có thể do file phải là file excel hoặc định dạng sai!', 'error');
            }
//            if (JFile::exists($filepath)) {
//                $this->delete($filepath);
//            }
//            var_dump($file['tmp_name']);
//            var_dump($filepath);exit();
            if (!JFile::upload($file['tmp_name'], $filepath)) {
                //!JFile::upload($file['tmp_name'], $filepath)
                //!copy($file['tmp_name'], $filepath)
                $mainframe->redirect('index.php?option=com_sim&task=edit&controller=sim', 'Error. Unable to upload file', 'error');
            } else {
                $mainframe->enqueueMessage(JText::_('Upload complete'));
//                $mainframe->redirect('index.php?option=com_sim&task=edit&controller=sim', 'Upload sim thành công', 'error');
            }
        } else {
            $mainframe->redirect('index.php', 'Invalid Request', 'error');
        }
    }
    function readxls(){
        $file 	= JRequest::getVar( 'Filedata', '', 'files', 'array' );
        $folder = 'xls';
        $filepath = JPath::clean(JPATH_COMPONENT.DS.helpers.DS.$folder.DS.strtolower($file['name']));
        //upload excel file onto server
        $this->upload($file,$filepath);
        require_once 'Excel/reader.php';
        // ExcelFile($filename, $encoding);
        $data = new Spreadsheet_Excel_Reader();
        // Set output Encoding.
        $data->setOutputEncoding('UTF-8');
        //read data from excel
        $data->read($filepath);
        $simbatch = array();
        for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
            if($data->sheets[0]['cells'][$i][1]==null){
                break;
            }else{
                for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
                    $k = trim($data->sheets[0]['cells'][1][$j]);
                    $simbatch[$i-2]->$k = $data->sheets[0]['cells'][$i][$j];
                }
            }
        }
        return $simbatch;
    }
    /**
     * Checks if the file can be uploaded
     *
     * @param array File information
     * @param string An error message to be returned
     * @return boolean
     */
    function canUpload($file, &$err )
    {
        $params = &JComponentHelper::getParams( 'com_media' );

        if(empty($file['name'])) {
            $err = 'Please input a file for upload';
            return false;
        }

        jimport('joomla.filesystem.file');
        if ($file['name'] !== JFile::makesafe($file['name'])) {
            $err = 'WARNFILENAME';
            return false;
        }

        $format = strtolower(JFile::getExt($file['name']));

        //$allowable = explode( ',', $params->get( 'upload_extensions' ));
        //$ignored = explode(',', $params->get( 'ignore_extensions' ));
        if (!$format=='xls')
        {
            $err = 'WARNFILETYPE';
            return false;
        }

        $maxSize = (int) $params->get( 'upload_maxsize', 0 );
        if ($maxSize > 0 && (int) $file['size'] > $maxSize)
        {
            $err = 'WARNFILETOOLARGE';
            return false;
        }
        return true;
    }

    function parseSize($size)
    {
        if ($size < 1024) {
            return $size . ' bytes';
        }
        else
        {
            if ($size >= 1024 && $size < 1024 * 1024) {
                return sprintf('%01.2f', $size / 1024.0) . ' Kb';
            } else {
                return sprintf('%01.2f', $size / (1024.0 * 1024)) . ' Mb';
            }
        }
    }
}